package io.github.enbool.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.MDC;
import org.springframework.security.oauth2.common.exceptions.UnauthorizedUserException;

import io.github.enbool.domain.Organization;
import io.github.enbool.domain.User;


/**
 * 用户工具类
 * 
 * @author 晓风轻 https://xwjie.github.io/PLMCodeTemplate/
 *
 */
public class UserUtil {

  private final static ThreadLocal<User> tlUser = new ThreadLocal<>();

  private final static ThreadLocal<String> tlIP = new ThreadLocal<>();

  public static final String KEY_USER = "user";
  public static final String KEY_IP = "IP";

  public static void setUser(User user) {
    tlUser.set(user);

    // 把用户信息放到log4j
    MDC.put(KEY_USER, user.getId());
  }
  
  public static void setIP(HttpServletRequest request) {
	 
	  String IP = IPUtil.getIP(request);
	  tlIP.set(IP);

      // 把IP放到log4j
      MDC.put(KEY_IP, IP);
  }
  
  public static String getIp() {
	  return tlIP.get();
  }

  /**
   * 如果没有登录，返回null
   * 
   * @return
   */
  public static User getUserIfLogin() {
    return tlUser.get();
  }

  /**
   * 如果没有登录会抛出异常
   * 
   * @return
   */
  public static User getUser() {
	  User user = tlUser.get();

    if (user == null) {
      throw new UnauthorizedUserException("用户未登录");
    }

    return user;
  }

  /**
   * 获得当前User的Organization
   * 如果没有登录会抛出异常
   * 
   * @return
   */
  public static Organization getUserOrganization() {
	  User user = (User) getUser();

    if (user == null) {
      throw new UnauthorizedUserException("用户未登录");
    }

    return user.getOrganization();
  }

  public static void clearAllUserInfo() {
    tlUser.remove();   
    tlIP.remove();
    
    MDC.remove(KEY_USER);
    MDC.remove(KEY_IP);
  }
}
